package com.nervenets.web.controller.handler.admin.wealth;

import com.nervenets.web.controller.handler.SessionHandler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.enumeration.*;
import com.nervenets.web.rabbitmq.FlowMessage;
import com.nervenets.web.rabbitmq.FlowType;
import com.nervenets.web.redis.domain.user.UserStored;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

public class UserWealthChangeHandler extends SessionHandler<UserWealthChangeParams> {
    @Override
    public ArrayList<Role> allowRoles() {
        return Role.administrator();
    }

    @Override
    public boolean needLog() {
        return false;
    }

    @Override
    public String handle(UserWealthChangeParams params, HttpServletRequest request) throws Exception {
        final long surplus = globalService.getUserWealthOfMoney(params.getTargetUserId(), WealthType.money);
        if (params.getOffset() > 10000000) return errorMessage(MessageCode.code_444, "单次变动金额不能超过一万");
        if (surplus + params.getOffset() < 0) return errorMessage(MessageCode.code_444, "变动后，用户资产为负，请重新填写变动值");

        if (!globalVariablesService.canProceedCustom("UserWealthChange" + params.getTargetUserId(), 300)) {
            return errorMessage(MessageCode.code_444, "在五分钟内，每个用户只能做一次资产变动，防止重复操作！");
        }

        final UserStored user = globalService.getUser(params.getTargetUserId());
        if (null == user) return errorMessage(MessageCode.code_404, "用户不存在");

        final FlowMessage message = new FlowMessage(params.getTargetUserId(), FlowType.wealthChange, getIp(request), params.getUserId());
        message.addData("offset", params.getOffset());
        message.addData("operateType", OperateType.human);
        message.addData("detail", params.getReason());
        message.addData("payType", PayType.surplus.name());
        message.addData("unionType", UnionType.manager.name());
        message.addData("flowStatus", FlowStatus.success.name());
        messageProducer.flow(message);

        return successMessage();
    }

    @Override
    public String result() {
        return null;
    }
}
